package com.bonc.modules.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.bonc.common.utils.*;
import com.bonc.datasource.annotation.DataSource;
import com.bonc.modules.business.entity.*;
import com.bonc.modules.business.service.FileSystemService;
import com.bonc.modules.business.service.TbWorkOederDistributionService;
import com.bonc.modules.business.service.TbWorkOrderInfoService;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.SchemaTypeSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.bonc.modules.business.dao.TbWorkOrderReplyDao;
import com.bonc.modules.business.service.TbWorkOrderReplyService;

import javax.annotation.Resource;

@DataSource("data")
@Service("tbWorkOrderReplyService")
public class TbWorkOrderReplyServiceImpl extends ServiceImpl<TbWorkOrderReplyDao, TbWorkOrderReplyEntity> implements TbWorkOrderReplyService {

    @Resource
    private TbWorkOrderReplyDao tbWorkOrderReplyDao;

    @Autowired
    private TbWorkOrderReplyService tbWorkOrderReplyService;

    @Autowired
    private TbWorkOrderInfoService tbWorkOrderInfoService;

    @Autowired
    private TbWorkOederDistributionService tbWorkOederDistributionService;

    @Autowired
    private FileSystemService fileSystemService;

    @Value("${iosServer.downloadUrl}")
    private String downloadUrl;

    @Value("${iosServer.uploadUrl}")
    private String uploadUrl;

    /**
     * 申请单文件下载路径
     */
    @Value("${downloadPath}")
    private String downloadPath;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TbWorkOrderReplyEntity> page = this.page(
                new Query<TbWorkOrderReplyEntity>().getPage(params),
                new QueryWrapper<TbWorkOrderReplyEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public boolean save(TbWorkOrderReplyEntity tbWorkOrderReply) {
        return SqlHelper.retBool(this.getBaseMapper().insert(tbWorkOrderReply));
    }

    @Override
    public boolean updateById(TbWorkOrderReplyEntity tbWorkOrderReply) {
        return SqlHelper.retBool(this.getBaseMapper().updateById(tbWorkOrderReply));

    }

    @Override
    public List<TbWorkOrderReplyEntity> list(Wrapper<TbWorkOrderReplyEntity> queryWrapper){
        return this.getBaseMapper().selectList(queryWrapper);
    }

    @Override
    public AtomicReference<String> replyOrderService() {
        LambdaQueryWrapper<TbWorkOrderReplyEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbWorkOrderReplyEntity::getStatus,"0");//OA端处理完成  才能回复
        List<TbWorkOrderReplyEntity> list = tbWorkOrderReplyService.list(queryWrapper);
        AtomicReference<String> res = new AtomicReference<>("");
        AtomicReference<String> req = new AtomicReference<>("");
        list.forEach(orderReply->{
            String url = "http://10.254.30.252:3900/api/v2/sync/CSVC/ReplyCSS";
            SupermanUtil util = new SupermanUtil();
            String accessToken = "2022021611194318072e4e2f524c3da560ac5f5f812cad-6229-1642389583";

            Calendar calendar= Calendar.getInstance();
            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMddHHmmss");
            SimpleDateFormat dateFormat1= new SimpleDateFormat("yyyyMMdd");
            String cutOffDay = dateFormat1.format(calendar.getTime());
            String timeStamp = dateFormat.format(calendar.getTime());
            String transIDO = timeStamp + System.currentTimeMillis();
            String sessionID = transIDO;
            String sign = "";
            String envFlag = "1";
            String version = "1.0.1";
            String signMethod = "MD5";
            String domain = "CSVC";
            String routeType = "00";
            String routeValue = "998";
            String busType = "CSVC";

            JSONObject content = new JSONObject();
            StringBuffer buffer = new StringBuffer();
            //判断此工单是否携带附件
            int flags = 0;
            if(!StringUtils.isBlank(orderReply.getAttachList())){
                System.out.println("附件不为空，获取文件后sftp到集团指定服务器目录下" + orderReply.getAttachList());
                String str[] = orderReply.getAttachList().split("\\|");
                for(int j=0;j<str.length;j++){
                    System.out.println(str[j]);
                    if(str.length > 1){
                        flags = j + 1;
                    }
                    String directory = str[j].substring(0,str[j].lastIndexOf("/")+1);
                    String fileName = str[j].substring(str[j].lastIndexOf("/")+1);
                    try {
                        //将239服务器文件下载到本地
                        String uploadPath = uploadUrl+directory;
                        fileSystemService.downloadFile1(uploadPath.substring(1,uploadPath.length()-1),fileName,"/home/cusguoxin/sftpTest/");
                        //fileSystemService.downloadFile1(uploadUrl,fileName,"D:\\TDownload\\");
                        // fileSystemService.deleteFile(downloadUrl,str[j]);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    //将文件统一上传至集团指定服务器目录下
                    //File file = new File("/home/cusguoxin/sftpTest/"+fileName);
                    //File file = new File("D:\\TDownload\\"+fileName);
                    try {
                        String fileNewName = fileSystemService.uploadFile4(uploadUrl,fileName,"/home/cusguoxin/sftpTest/",fileName,flags);
                        System.out.println(fileNewName);
                        if(j == str.length-1){
                            buffer.append(fileNewName);
                        }else{
                            buffer.append(fileNewName+"|");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            System.out.println(buffer);
            content.put("Identifier", orderReply.getIdentifier());
            content.put("HandlingOpinion", orderReply.getHandlingOpinion());
            content.put("Handler", orderReply.getHandler());
            content.put("HandlerInfor", orderReply.getHandlerInfor());
            content.put("AttachList", buffer);
            content.put("HandingTime", orderReply.getHandingTime());
            content.put("HandlerRank", orderReply.getHandlerRank());
            content.put("HandingDepartment", orderReply.getHandingDepartment());
            content.put("ImprovementMode", orderReply.getImprovementMode());
            content.put("ImprovementPoints", orderReply.getImprovementPoints());
            content.put("PackageCode", orderReply.getPackageCode());
            content.put("PackageName", orderReply.getPackageName());
            content.put("PromotionCode", orderReply.getPromotionCode());
            content.put("PromotionName", orderReply.getPromotionName());
            content.put("SelfEvaluation",orderReply.getSelfEvaluation());

            //通过工单编号获取到工单派发表四个字段数据
            TbWorkOederDistributionEntity order = tbWorkOederDistributionService.getById(orderReply.getIdentifier());
            if(order.getIdentySubtype().equals("0206")){//当工单子类型（IdentySubtype）为投诉焦点治理任务单（0206）时，工单派发字段需增加以下字段
                System.out.println("---------------------------" + order.getParaList());
                JSONArray jsonArray = JSONArray.fromObject(order.getParaList());
                net.sf.json.JSONObject jsonobj = net.sf.json.JSONObject.fromObject(jsonArray.getJSONObject(0));

                Map resMap = new HashMap();
                resMap.put("GovernanceMeasures", jsonobj.get("GovernanceMeasures"));
                resMap.put("goal", jsonobj.get("goal"));
                resMap.put("ProcessTime", jsonobj.get("ProcessTime"));
                resMap.put("Evaluation", jsonobj.get("Evaluation"));
                jsonArray = JSONArray.fromObject(resMap);
                orderReply.setParaList(jsonArray.toString());
                tbWorkOrderReplyService.updateById(orderReply);
                content.put("ParaList",orderReply.getParaList());
            }

            Map<String,Object> maps = new TreeMap<String,Object>();
            Iterator iterator = content.entrySet().iterator();
            while(iterator.hasNext())
            {
                Map.Entry<String,Object> entry = (Map.Entry<String,Object>) iterator.next();
                maps.put(entry.getKey(),entry.getValue());
            }
            maps.entrySet();

            //总体：所有研究对象的全体
            Map<String, Object> param = new TreeMap<>();
            param.put("cutOffDay", cutOffDay);
            param.put("timeStamp", timeStamp);
            param.put("transIDO", transIDO);
            param.put("sessionID", sessionID);
            param.put("envFlag", envFlag);
            param.put("accessToken", accessToken);
            param.put("version", version);
            param.put("domain", domain);
            param.put("signMethod", signMethod);
            param.put("routeType", routeType);
            param.put("routeValue", routeValue);
            param.put("busType", busType);
            param.put("content",JSONObject.toJSONString(maps));

            //字段参数升序排序
            param.entrySet();
            String appSecret = "r1v7w0E84j";//appSecret
            StringBuilder builder = new StringBuilder(appSecret);
            int i = 0;
            //将参数通过keyvalue的方式进行拼接  key传空值默认不拼接
            for (String key : param.keySet()) {
                Object value = param.get(key);
                if (value == null) { // 过滤空的key
                    continue;
                }
                builder.append(key).append(value.toString().trim());
                i++;
            }
            builder.append(appSecret);
            System.out.println(builder.toString());
            try {
                sign = SignUtil.checkMD5(builder.toString());
                param.put("sign", sign);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }

            /*req.set(JSON.toJSONString(param));
            res.set(util.sendPost(url, req.get()));
            System.out.println(orderReply.getIdentifier());
            TbWorkOrderInfoEntity tbWorkOrderInfo = new TbWorkOrderInfoEntity();
            tbWorkOrderInfo.setIdentifier(orderReply.getIdentifier());
            tbWorkOrderInfo.setState("04");
            boolean flag = tbWorkOrderInfoService.updateById(tbWorkOrderInfo);
            System.out.println(flag);
            if(flag == true){
                orderReply.setStatus("1");
                tbWorkOrderReplyService.updateById(orderReply);
            }*/
        });
        return res;
    }

    @Override
    public AtomicReference<String> postCurrencyCSS(TbWorkOrderCurrencyEntity tbWorkOrderCurrencyEntity) {
        //需要判断触发中途意见的接口对应工单是否已经调用工单回复接口

        AtomicReference<String> res = new AtomicReference<>("");
        AtomicReference<String> req = new AtomicReference<>("");

        String url = "http://10.254.30.252:3900/api/v2/sync/CSVC/CurrencyCSS";
        SupermanUtil util = new SupermanUtil();

        JSONObject content = new JSONObject();
        content.put("InterfaceType", "HandlingComment");
        content.put("Identifier", tbWorkOrderCurrencyEntity.getIdentifier());
        content.put("LaunchCompany", tbWorkOrderCurrencyEntity.getLaunchCompany());
        content.put("ForwardCompany", tbWorkOrderCurrencyEntity.getForwardCompany());

        Map resMap = new HashMap();
        resMap.put("Identifier", tbWorkOrderCurrencyEntity.getIdentifier());
        resMap.put("HandlingComment", tbWorkOrderCurrencyEntity.getHandlingComment());
        resMap.put("AddComment", tbWorkOrderCurrencyEntity.getAddComment());
        resMap.put("Handler", tbWorkOrderCurrencyEntity.getHandler());
        resMap.put("HandlerInfor", tbWorkOrderCurrencyEntity.getHandlerInfor());
        resMap.put("HandingTime", tbWorkOrderCurrencyEntity.getHandingTime());
        resMap.put("HandlerRank", tbWorkOrderCurrencyEntity.getHandlerRank());
        resMap.put("HandingDepartment", tbWorkOrderCurrencyEntity.getHandingDepartment());
        resMap.put("AttachList", tbWorkOrderCurrencyEntity.getAttachList());
        //赋值到ParaList
        content.put("ParaList",JSONArray.fromObject(resMap));

        Map<String, Object> param = ResolveParamUtils.getAllParam(content);

        req.set(JSON.toJSONString(param));
        res.set(util.sendPost(url, req.get()));

        //调用中途意见接口后，更新回复表处理人相关信息
        TbWorkOrderReplyEntity orderReply = new TbWorkOrderReplyEntity();
        orderReply.setIdentifier(tbWorkOrderCurrencyEntity.getIdentifier());
        orderReply.setHandler(tbWorkOrderCurrencyEntity.getHandler());
        orderReply.setHandlerInfor(tbWorkOrderCurrencyEntity.getHandlerInfor());
        orderReply.setHandlerRank(tbWorkOrderCurrencyEntity.getHandlerRank());
        orderReply.setHandingDepartment(tbWorkOrderCurrencyEntity.getHandingDepartment());
        orderReply.setHandingTime(tbWorkOrderCurrencyEntity.getHandingTime());
        tbWorkOrderReplyService.updateById(orderReply);

        //更新工单信息表处理人相关信息
        TbWorkOrderInfoEntity tbWorkOrderInfo = new TbWorkOrderInfoEntity();
        tbWorkOrderInfo.setIdentifier(tbWorkOrderCurrencyEntity.getIdentifier());
        tbWorkOrderInfo.setHandler(tbWorkOrderCurrencyEntity.getHandler());
        tbWorkOrderInfo.setHandlerContactInfor(tbWorkOrderCurrencyEntity.getHandlerInfor());
        tbWorkOrderInfo.setHandingTime(tbWorkOrderCurrencyEntity.getHandingTime());
        tbWorkOrderInfo.setHandingDepartment(tbWorkOrderCurrencyEntity.getHandingDepartment());
        tbWorkOrderInfoService.updateById(tbWorkOrderInfo);

        return res;
    }

    @Override
    public ReplyCommon ReplyCSS(TbCommonParamInfoEntity tbCommonParamValue) throws IllegalAccessException {
        Map<String, Object> param = new TreeMap();
        String content = "";
        String rspCode = "";
        String rspDesc = "";

        boolean flag = true;
        String timeStamp = tbCommonParamValue.getTimeStamp();
        String transIDO = tbCommonParamValue.getTransIDO();
        String sessionID = tbCommonParamValue.getSessionID();
        String sign = tbCommonParamValue.getSign();
        String envFlag = tbCommonParamValue.getEnvFlag();
        String version = tbCommonParamValue.getVersion();
        String domain = tbCommonParamValue.getDomain();
        String routeType = tbCommonParamValue.getRouteType();
        String routeValue = tbCommonParamValue.getRouteValue();
        String busType = tbCommonParamValue.getBusType();
        String providePartyID = "CSVB3510";
        if ((StringUtils.isBlank(timeStamp)) || (StringUtils.isBlank(transIDO)) || (StringUtils.isBlank(sessionID)) || (StringUtils.isBlank(sign)) ||
                (StringUtils.isBlank(envFlag)) || (StringUtils.isBlank(version)) || (StringUtils.isBlank(domain)) || (StringUtils.isBlank(routeType)) ||
                (StringUtils.isBlank(routeValue)) || (StringUtils.isBlank(busType)))
        {
            rspCode = "20101";
            rspDesc = "缺少必须的参数";
            flag = false;
        }
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
        String cutOffDay = dateFormat.format(calendar.getTime());
        //String handingTime = dateFormat1.format(calendar.getTime());
        if (flag)
        {
            String appSecret = "YRZ803Rxvx";
            Field[] fields = tbCommonParamValue.getClass().getDeclaredFields();
            for (Field field : fields)
            {
                field.setAccessible(true);
                String name = new String(field.getName());
                if ((!name.equals("sign")) && (!name.equals("userPartyID"))) {
                    param.put(name, field.get(tbCommonParamValue));
                }
            }
            param.entrySet();
            StringBuilder builder = new StringBuilder(appSecret);
            int i = 0;
            for (String key : param.keySet())
            {
                Object value = param.get(key);
                if (value != null)
                {
                    builder.append(key).append(value.toString().trim());
                    i++;
                }
            }
            builder.append(appSecret);

            /* 本地sign校验鉴权暂时屏蔽  网状网已经校验
            String signjy = SignUtil.checkMD5(builder.toString());
            if ((sign == signjy) || (sign.equals(signjy)))
            {

            }
            else
            {
                rspCode = "20207";
                rspDesc = "非法的签名";
            }*/

            content = tbCommonParamValue.getContent();
            TbWorkOrderReplyEntity orderReply = JSONObject.parseObject(content, TbWorkOrderReplyEntity.class);
            if (StringUtils.isBlank(orderReply.getIdentifier()))
            {
                rspCode = "20101";
                rspDesc = "缺少必须的参数";
            }
            else
            {
                if(!StringUtils.isBlank(orderReply.getAttachList())){
                    orderReply.setAnnexStatus("1");
                }

                orderReply.setStatus("1");
                boolean num = this.tbWorkOrderReplyService.save(orderReply);

                //集团回复之后需要更新工单信息表数据
                TbWorkOrderInfoEntity tbWorkOrderInfo = new TbWorkOrderInfoEntity();
                tbWorkOrderInfo.setIdentifier(orderReply.getIdentifier());
                tbWorkOrderInfo.setState("04");
                tbWorkOrderInfo.setHandingTime(orderReply.getHandingTime());
                tbWorkOrderInfo.setHandingDepartment(orderReply.getHandingDepartment());
                tbWorkOrderInfo.setHandingOpinions(orderReply.getHandlingOpinion());
                tbWorkOrderInfo.setHandlerContactInfor(orderReply.getHandlerInfor());
                tbWorkOrderInfo.setHandler(orderReply.getHandler());
                tbWorkOrderInfoService.updateById(tbWorkOrderInfo);

                if (num == true)
                {
                    rspCode = "00000";
                    rspDesc = "success";
                }
                else
                {
                    rspCode = "20000";
                    rspDesc = "基础服务系统内部错误";
                }
            }

        }
        return ReplyCommon.ok(transIDO, cutOffDay, providePartyID, rspCode, rspDesc);
    }

    @Override
    public List<TbWorkOrderReplyEntity> getOrderReplyDistributionList() {
        return tbWorkOrderReplyDao.getOrderReplyDistributionList();
    }

    @Override
    public TbWorkOrderReplyEntity getById(String id) {
        return this.getBaseMapper().selectById(id);
    }

    @Scheduled(cron = "0 */5 * * * ?")
    public void getOrderReplyAttachList() throws Exception {
        List<TbWorkOrderReplyEntity> list = tbWorkOrderReplyService.getOrderReplyDistributionList();
        System.out.println("attachReplylist-------"+list.size());
        for(int i=0;i<list.size();i++){
            TbWorkOrderReplyEntity order = list.get(i);
            System.out.println("执行定时任务扫描sftp下载申请单回复文件到本地......");
            String str[] = order.getAttachList().split("\\|");
            for(int j=0;j<str.length;j++){
                String fileName = str[j];
                System.out.println(fileName);
                fileSystemService.downloadFile(downloadUrl,str[j],downloadPath);
                fileSystemService.deleteFile(downloadUrl,str[j]);
            }
            //将工单派发表附件状态改为2
            order.setAnnexStatus("2");
            tbWorkOrderReplyService.updateById(order);
        }
    }
}
